﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Core.DataAccess.IRepositories;

namespace Core.DataAccess.Repositories
{
    [Export(typeof(IProfileRepository))]
    public class ProfileRepository : IProfileRepository
    {
        private Connection conn;
        public ProfileRepository()
        {
            conn = new Connection();
        }

        public Profile GetProfileByAccoutID(int AccountID)
        {
            Profile profile;
            using (MXHEntities context = conn.GetContext())
            {
                profile = context.Profiles.SingleOrDefault(n => n.AccountID.Equals(AccountID));
            }
            return profile;
        }

        public void SaveProfile(Profile profile)
        {
            using (MXHEntities context = conn.GetContext())
            {
                if (profile.ProfileID > 0)
                {
                    context.Profiles.Attach(new Profile { ProfileID = profile.ProfileID });
                    context.Profiles.ApplyCurrentValues(profile);
                }
                else
                {
                    context.Profiles.AddObject(profile);
                }
                context.SaveChanges();
            }                
        }

        public void DeleteProfileByAccountID(int accountID)
        {
            using (MXHEntities context = conn.GetContext())
            {
                var item = from pro in context.Profiles
                           where pro.AccountID == accountID
                           select pro;
                if (item.Count() > 0)
                {
                    Profile profile = item.FirstOrDefault();
                    context.Profiles.DeleteObject(profile);
                    context.SaveChanges();
                }
            }
        }
    }
}
